<template>
  <div class="sheet-container">
    <!-- 顶部工具栏 -->
    <div class="sheet-header">
      <div class="left-section">
        <el-button @click="getBack">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <el-input
          v-model="sheetName"
          placeholder="未命名表格"
          class="sheet-name-input"
          @blur="getSaveTitle"
        />
        <div class="sheet-status">
          <el-icon v-if="isSaving"><Edit /></el-icon>
          <el-icon v-else><Select /></el-icon>
          <span>{{ isSaving ? "未保存" : "已保存" }} Ctrl + S保存</span>
        </div>
        <div class="sheet-button">
          <input
            type="file"
            ref="importFileRef"
            @change="importFileHandle"
            style="display: none"
          />
          <el-button type="primary" @click="importFileRef.click()"> 导入 </el-button>
          <el-button
            type="primary"
            @click="exportExcel(sheetName, luckysheet.getAllSheets())"
          >
            下载
          </el-button>
        </div>
      </div>

      <div class="collaborators">
        <div class="active-users">
          <el-tooltip
            v-for="user in activeUsers"
            :key="user._id"
            :content="user.username"
            placement="bottom"
          >
            <div class="user-avatar">
              <el-avatar :size="32" :src="user.avatar">
                {{ user.username }}
              </el-avatar>
              <div class="user-status"></div>
            </div>
          </el-tooltip>
        </div>
        <el-button type="primary" @click="getShareDialog">
          <el-icon><Share /></el-icon>
          分享
        </el-button>
      </div>
    </div>
    <div class="sheet-content">
      <div id="luckysheet" style="width: 100%; height: calc(100vh - 57px)"></div>
    </div>
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" align-center>
      <span>当前表格未保存您确定要退出吗</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="router.push('/dashboard')"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <ShareDialog
      :sheetName="sheetName"
      @removeSheetUser="removeSheetUser"
      :authorId="authorId"
      :sheetId="route.params.id"
      :permissionsUsers="permissionsUsers"
      ref="shareDialogEl"
    ></ShareDialog>
  </div>
</template>

<script setup lang="ts">
import LuckyExcel from "luckyexcel";
import pako from "pako";
import { getSheet, updateSheet } from "../api/sheet/index.ts";
import { ElMessage } from "element-plus";
import "luckysheet/dist/css/luckysheet.css";
import luckysheet from "luckysheet";
import WebSocketService from "../utils/websocket";
import { onMounted, ref, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ArrowLeft, Edit, Select, Share } from "@element-plus/icons-vue";
import { exportExcel } from "../utils/exportsheet.ts";
import ShareDialog from "../components/ShareDialog.vue";
const route = useRoute();
const router = useRouter();
const importFileRef = ref();
let permissionsUsers = ref([]);
document.addEventListener("keydown", function (event) {
  if (event.ctrlKey && event.key === "s") {
    event.preventDefault();
    saveSheet();
  }
});
const centerDialogVisible = ref(false);
const sheetName = ref("未命名表格");
const sheetId = ref(route.params.id)
const authorId = ref();
const isSaving = ref(false);
const shareDialogEl = ref();
let activeUsers = ref([]);
// 协作相关

const getLuckySheet = async () => {
  let result: any = await getSheet({
    id: route.params.id as string,
    userId: JSON.parse(localStorage.getItem("user") as string)._id,
  });
  if (result.code == 400) {
    ElMessage.error(result.data);
    router.push("/dashboard");
    return;
  }
  initLuckysheet();
  permissionsUsers.value = result.data.permissionsId;
  authorId.value = result.data.author;
  sheetName.value = result.data.title;
};
const saveSheet = async () => {
  let result: any = await updateSheet({
    id: route.params.id as string,
    content: pako.deflate(
      new TextEncoder().encode(JSON.stringify(luckysheet.getluckysheetfile()))
    ),
    author: JSON.parse(localStorage.getItem("user") as string)._id
  });
  if (result.code === 200) {
    // 更新成功后的操作
    isSaving.value = false;
  } else {
    console.error("更新失败", result.msg);
  }
};
const initLuckysheet = () => {
  const options = {
    container: "luckysheet",
    lang: "zh",
    allowUpdate: true,
    loadUrl: `http://localhost:3000/api/sheet/getSheet?id=${route.params.id}&userId=${
      JSON.parse(localStorage.getItem("user") as string)._id
    }&type=sheet`,
    updateUrl: `ws://localhost:3000?type=luckysheet&id=${
      JSON.parse(localStorage.getItem("user") as string)._id
    }&name=${JSON.parse(localStorage.getItem("user") as string).username}&sheetId=${
      route.params.id
    }`,
    hook: {
      cellUpdated: async function () {
        saveSheet();
      },
      cellEditBefore: async function () {
        isSaving.value = true;
      },
    },
  };

  // 销毁旧的Luckysheet实例
  if (luckysheet.luckysheet) {
    luckysheet.destroy();
  }

  // 创建新的Luckysheet实例
  luckysheet.create(options);
};
const getBack = () => {
  if (isSaving.value) {
    centerDialogVisible.value = true;
    return;
  }
  router.push("/dashboard");
};
const importFileHandle = (e: { target: { files: any } }) => {
  let { files } = e.target;
  LuckyExcel.transformExcelToLucky(
    files[0],
    (exportJson: { info: any; sheets: any }, _luckysheetfile: any) => {
      let { info, sheets } = exportJson;

      luckysheet.setWorkbookName(info.name);

      sheets.forEach((sheet: any) => {
        // sheet 便是每一个 sheet 页，需要根据实际的数量动态创建
        luckysheet.setSheetAdd({
          sheetObject: sheet,
        });
      });
      // 清空
      importFileRef.value.value = "";
    }
  );
};
const getSaveTitle = async () => {
  let result: any = await updateSheet({
    id: route.params.id as string,
    title: sheetName.value,
    author: JSON.parse(localStorage.getItem("user") as string)._id,
  });
  if (result.code === 200) {
    ElMessage.success("标题修改成功");
  } else {
    ElMessage.error("标题修改失败");
  }
};
const getShareDialog = () => {
  shareDialogEl.value.showShareDialog = true;
};
onMounted(async () => {
  getLuckySheet();
  WebSocketService.connect(route.params.id);
  setTimeout(() => {
      WebSocketService.send({
        type: "5",
        userInfo: JSON.parse(localStorage.getItem("user") as string),
        sheetId: route.params.id,
        status: true,
      });
      WebSocketService.socket.onmessage = (event: { data: string }) => {
        let data = JSON.parse(event.data);
        activeUsers.value = data.userInfo;
      };
    }, 1000);
});
onBeforeUnmount(() => {
  WebSocketService.send({ type: "3" });
  WebSocketService.send({
    type: "5",
    userInfo: JSON.parse(localStorage.getItem("user") as string),
    sheetId: sheetId.value,
    status: false,
  });
});
const removeSheetUser = (val: never[]) => {
  permissionsUsers.value = val;
};
</script>

<style scoped lang="scss">
:deep(#luckysheet_info_detail) {
  display: none !important;
}
:deep(#luckysheet-sheets-leftscroll) {
  display: none !important;
}
:deep(.sheet-name) {
  display: none !important;
}
:deep(.luckysheet-sheet-container) {
  padding: 0 45px !important;
}
:deep(#luckysheet-sheets-rightscroll) {
  display: none !important;
}
.sheet-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;

  .sheet-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    background: white;
    border-bottom: 1px solid #dcdfe6;

    .left-section {
      display: flex;
      align-items: center;
      gap: 12px;

      .sheet-name-input {
        width: 200px;
      }

      .sheet-status {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #909399;
        font-size: 12px;
      }
    }

    .collaborators {
      display: flex;
      align-items: center;
      gap: 16px;

      .active-users {
        display: flex;
        gap: 4px;

        .user-avatar {
          position: relative;
          border-radius: 50%;

          .user-status {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #67c23a;
            border: 2px solid white;
          }
        }
      }
    }
  }
}
</style>
